//
//  listViewModel.swift
//  todoList
//
//  Created by Aoyun on 02/01/2025.
//

import Foundation

@Observable class ListViewModel {
    var todoList: [listModel] = [] {
        didSet {
            setToDoList()
        }
    }

    var forkey: String = "todolist123"

    init() {
        getToDoList()
    }

    func getToDoList() {
        guard
            let data = UserDefaults.standard.data(forKey: forkey),
            let saveDoList = try? JSONDecoder().decode([listModel].self, from: data)
        else { return }
        
        self.todoList = saveDoList
    }

    func deleteList(index: IndexSet) {
        todoList.remove(atOffsets: index)
    }

    func moveList(from: IndexSet, to: Int) {
        todoList.move(fromOffsets: from, toOffset: to)
    }

    func addList(item: String) {
        let newItem = listModel(toDo: item, isDo: false)
        todoList.append(newItem)
    }

    func changeIsDo(item: listModel) {
        if let index = todoList.firstIndex(where: { $0.id == item.id }) {
            todoList[index] = item.changeIsDo()
        }
    }

    func setToDoList() {
        if let data = try? JSONEncoder().encode(todoList) {
            UserDefaults.standard.set(data, forKey: forkey)
        }
    }
}
